package com.example.service;

import com.example.Entity.Message;
import com.example.Entity.Product;
import com.example.Entity.ProductVo;
import com.example.Repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.List;

@Service
public class ProductService {

    @Autowired
    private ProductRepository productRepository;

    public ProductVo findAll() {
        ProductVo productVo = new ProductVo();
        long count = productRepository.count();
        List<Product> products = productRepository.findAll();
        productVo.setTotalCount((int) count);
        productVo.setProducts(products);
        productVo.setPages(1);
        return productVo;
    }

    @Transactional
    public Message save(Product product) {
        Message message = new Message();
        Product result = productRepository.save(product);
        if (!ObjectUtils.isEmpty(result)) {
            message.setCode("success");
            message.setMessage("成功");
        } else {
            message.setMessage("false");
            message.setMessage("失败！");
        }
        return message;
    }

    public Product getById(Integer id) {
        return productRepository.findById(id).get();
    }

    @Transactional
    public Message updateById(Integer id, Product product) {
        Message message = new Message();
        product.setId(id);
        Product result = productRepository.save(product);
        if (!ObjectUtils.isEmpty(result)) {
            message.setCode("success");
            message.setMessage("成功");
        } else {
            message.setMessage("false");
            message.setMessage("失败！");
        }
        return message;
    }

    @Transactional
    public Message delById(@PathVariable("id") Integer id) {
        Message message = new Message();
        productRepository.deleteById(id);
        message.setCode("success");
        message.setMessage("成功");
        return message;
    }
}
